﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Runtime.InteropServices;
using Interop.jmail;
using UDS.Components;

namespace UDS.Entity
{
    /// <summary>
    /// Provide functionalities for external mails (POP3).
    /// </summary>
    public static class ExternalMail
    {
        /// <summary>
        /// 外部邮件设置保存
        /// </summary>
        public static bool ExtSaveSetting(string username, string title, string email, bool smtpauth, string smtpserver, string smtpusername, string smtppassword, string smtpport, string popserver, string popusername, string poppassword, int popport, bool isdelafterread, bool isreceivenew, int timeout, int orderid)
        {
            // create data object and params
            var parameters = new[]
            {
                Database.MakeInParam("@Username", SqlDbType.NVarChar, 50, username),
                Database.MakeInParam("@Title", SqlDbType.NVarChar, 30, title),
                Database.MakeInParam("@Email", SqlDbType.NVarChar, 200, email),
                Database.MakeInParam("@SmtpAuth", SqlDbType.Bit, 1, smtpauth),
                Database.MakeInParam("@SmtpServer", SqlDbType.NVarChar, 100, smtpserver),
                Database.MakeInParam("@SmtpUsername", SqlDbType.NVarChar, 30, smtpusername),
                Database.MakeInParam("@SmtpPassword", SqlDbType.NVarChar, 30, smtppassword),
                Database.MakeInParam("@SmtpPort", SqlDbType.Int, 10, smtpport),
                Database.MakeInParam("@PopServer", SqlDbType.NVarChar, 100, popserver),
                Database.MakeInParam("@PopUsername", SqlDbType.NVarChar, 30, popusername),
                Database.MakeInParam("@PopPassword", SqlDbType.NVarChar, 30, poppassword),
                Database.MakeInParam("@PopPort", SqlDbType.Int, 10, popport),
                Database.MakeInParam("@IsDelAfterRead", SqlDbType.Bit, 1, isdelafterread),
                Database.MakeInParam("@IsReceiveNew", SqlDbType.Bit, 1, isreceivenew),
                Database.MakeInParam("@TimeOut", SqlDbType.Int, 10, timeout),
                Database.MakeInParam("@OrderID", SqlDbType.Int, 10, orderid)
            };


            using (var db = new Database())
            {
                db.RunProc("dbo.sproc_MailExtSetAdd", parameters);
            }
            return true;
        }

        /// <summary>
        /// 清空某用户外部邮件设置
        /// </summary>
        /// <param name="Username">用户名</param>
        public static bool ExtClearSettings(string Username)
        {
            var parameters = new[]
            {
                Database.MakeInParam("@Username", SqlDbType.NVarChar, 50, Username),
            };

            using (var db = new Database())
            {
                db.RunProc("dbo.sproc_MailExtSetClear", parameters);
                return true;
            }
        }

        /// <summary>
        /// 获取可用到的设置的内容	
        /// </summary>
        public static SqlDataReader ExtGetAvaSetting(string Username)
        {
            // create data object and params
            var parameters = new[]
            {
                Database.MakeInParam("@Username", SqlDbType.NVarChar, 20, Username)
            };

            using (var db = new Database())
            {
                return db.RunDataReader("dbo.sproc_MailExtGetAvailabelSet", parameters);
            }
        }

        public static void ReceiveMails(string Username, int OrderID)
        {
            var jpop = new POP3();
            if (OrderID != 0)
            {
                using (SqlDataReader dataReader = ExtGetSetting(Username, OrderID))
                {
                    if (dataReader.Read())
                    {
                        if (dataReader["PopServer"].ToString() != "" && dataReader["PopUsername"].ToString() != "")
                        {
                            jpop.Connect(dataReader["PopUsername"].ToString(), dataReader["PopPassword"].ToString(), dataReader["PopServer"].ToString(), Int32.Parse(dataReader["PopPort"].ToString()));
                            for (int i = 1; i <= jpop.Count; i++)
                            {
                                Message Msg = jpop.Messages[i];
                                SaveExtMail(Msg, Username, dataReader["Email"].ToString(), jpop.GetMessageUID(i));
                            }
                            jpop.Disconnect();
                        }
                    }
                }
            }

            try
            {
                Marshal.ReleaseComObject(jpop);
            }
            catch
            {
                // Ignore all the exceptions
            }
        }

        /// <summary>
        /// 获取设置的内容	
        /// </summary>
        public static SqlDataReader ExtGetSetting(string Username, int OrderID)
        {
            // create data object and params
            var parameters = new[]
            {
                Database.MakeInParam("@Username", SqlDbType.NVarChar, 20, Username),
                Database.MakeInParam("@OrderID", SqlDbType.Int, 1, OrderID)
            };


            var db = new Database();
            return db.RunDataReader("dbo.sproc_MailExtGetSet", parameters);
        }

        /// <summary>
        /// 外部邮件主体保存
        /// </summary>
        private static void SaveExtMail(Message JMsg, string Username, string Email, string MessageID)
        {
            // create data object and params
            /*
			var parameters = new[] {
			   Database.MakeInParam("@MailID",  SqlDbType.NVarChar , 10, ""),
			   Database.MakeInParam("@Username",  SqlDbType.NVarChar, 300, Username),
			   Database.MakeInParam("@Email",  SqlDbType.NVarChar, 100,"" ),
			   Database.MakeInParam("@ReadFlag",  SqlDbType.Bit,1, 0),
			   Database.MakeInParam("@FolderID",  SqlDbType.Int, 20, 1),
			   Database.MakeInParam("@HeadersText",  SqlDbType.NVarChar, 1000, Msg.Headers.ToString()),
			   Database.MakeInParam("@Subject",  SqlDbType.NVarChar, 100, Msg.Subject.ToString()),
			   Database.MakeInParam("@TextContent",  SqlDbType.NVarChar , 3000, Msg.Text.ToString()),
			   Database.MakeInParam("@HtmlContent",  SqlDbType.NVarChar, 3000, Msg.HTMLBody.ToString()),
			   Database.MakeInParam("@FromName",  SqlDbType.NVarChar, 300, Msg.FromName.ToString()),
			   Database.MakeInParam("@FromEmail",  SqlDbType.NVarChar, 200, Msg.From.ToString()),
			   Database.MakeInParam("@CcTo",  SqlDbType.NVarChar, 200,""),
			   Database.MakeInParam("@BccTo",  SqlDbType.NVarChar, 200, ""),
			   Database.MakeInParam("@Replyto",  SqlDbType.NVarChar, 200, Msg.ReplyTo.ToString()),
			   Database.MakeInParam("@SendDate",  SqlDbType.DateTime, 30, DateTime.Now),
			   Database.MakeInParam("@BodySize",  SqlDbType.NVarChar , 20, ""),
			   Database.MakeInParam("@Size",  SqlDbType.Int, 5,12)
									 
            };
			*/
            var parameters = new[]
            {
                Database.MakeInParam("@MailID", SqlDbType.NVarChar, 100, MessageID),
                Database.MakeInParam("@Username", SqlDbType.NVarChar, 300, Username),
                Database.MakeInParam("@Email", SqlDbType.NVarChar, 100, Email),
                Database.MakeInParam("@ReadFlag", SqlDbType.Bit, 1, 0),
                Database.MakeInParam("@FolderID", SqlDbType.Int, 20, 1),
                Database.MakeInParam("@HeadersText", SqlDbType.NVarChar, 1000, JMsg.Headers.ToString()),
                Database.MakeInParam("@Subject", SqlDbType.NVarChar, 100, JMsg.Subject),
                Database.MakeInParam("@TextContent", SqlDbType.NVarChar, 3000, JMsg.Text),
                Database.MakeInParam("@HtmlContent", SqlDbType.NVarChar, 3000, JMsg.HTMLBody),
                Database.MakeInParam("@FromName", SqlDbType.NVarChar, 300, JMsg.FromName),
                Database.MakeInParam("@FromEmail", SqlDbType.NVarChar, 200, ""),
                Database.MakeInParam("@CcTo", SqlDbType.NVarChar, 200, ""),
                Database.MakeInParam("@BccTo", SqlDbType.NVarChar, 200, ""),
                Database.MakeInParam("@Replyto", SqlDbType.NVarChar, 200, ""),
                Database.MakeInParam("@SendDate", SqlDbType.DateTime, 30, DateTime.Parse(JMsg.Date.ToString())),
                Database.MakeInParam("@BodySize", SqlDbType.NVarChar, 20, ""),
                Database.MakeInParam("@Size", SqlDbType.Int, 5, 12)
            };

            using (var db = new Database())
            {
                db.RunProc("dbo.sproc_MailExtMailAdd", parameters);
            }
        }
    }
}
